//
//  AccountManager.m
//
//  Created by   on 2018/6/2
//  Copyright (c) 2018 __MyCompanyName__. All rights reserved.
//

#import "AccountManager.h"
#import "AuthorizationManager.h"
#import "DataLocalManager.h"

NSString *const kAccountManagerStatus = @"status";
NSString *const kAccountManagerUserId = @"userId";
NSString *const kAccountManagerUserName = @"userName";
NSString *const kAccountManagerId = @"id";
NSString *const kAccountManagerRegTime = @"regTime";
NSString *const kAccountManagerUserPwd = @"userPwd";
NSString *const kAccountManagerEmail = @"email";
NSString *const kAccountManagerNickName = @"nickName";


@interface AccountManager ()

- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict;

@end

@implementation AccountManager

@synthesize status = _status;
@synthesize userId = _userId;
@synthesize userName = _userName;
@synthesize internalBaseClassIdentifier = _internalBaseClassIdentifier;
@synthesize regTime = _regTime;
@synthesize userPwd = _userPwd;
@synthesize email = _email;
@synthesize nickName = _nickName;


+ (instancetype)modelObjectWithDictionary:(NSDictionary *)dict
{
    return [[self alloc] initWithDictionary:dict];
}

- (instancetype)initWithDictionary:(NSDictionary *)dict
{
    self = [super init];
    
    // This check serves to make sure that a non-NSDictionary object
    // passed into the model class doesn't break the parsing.
    if(self && [dict isKindOfClass:[NSDictionary class]]) {
            self.status = [[self objectOrNilForKey:kAccountManagerStatus fromDictionary:dict] doubleValue];
            self.userId = [self objectOrNilForKey:kAccountManagerUserId fromDictionary:dict];
            self.userName = [self objectOrNilForKey:kAccountManagerUserName fromDictionary:dict];
            self.internalBaseClassIdentifier = [self objectOrNilForKey:kAccountManagerId fromDictionary:dict];
            self.regTime = [self objectOrNilForKey:kAccountManagerRegTime fromDictionary:dict];
            self.userPwd = [self objectOrNilForKey:kAccountManagerUserPwd fromDictionary:dict];
            self.email = [self objectOrNilForKey:kAccountManagerEmail fromDictionary:dict];
            self.nickName = [self objectOrNilForKey:kAccountManagerNickName fromDictionary:dict];

    }
    
    return self;
    
}

- (NSDictionary *)dictionaryRepresentation
{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
    [mutableDict setValue:[NSNumber numberWithDouble:self.status] forKey:kAccountManagerStatus];
    [mutableDict setValue:self.userId forKey:kAccountManagerUserId];
    [mutableDict setValue:self.userName forKey:kAccountManagerUserName];
    [mutableDict setValue:self.internalBaseClassIdentifier forKey:kAccountManagerId];
    [mutableDict setValue:self.regTime forKey:kAccountManagerRegTime];
    [mutableDict setValue:self.userPwd forKey:kAccountManagerUserPwd];
    [mutableDict setValue:self.email forKey:kAccountManagerEmail];
    [mutableDict setValue:self.nickName forKey:kAccountManagerNickName];

    return [NSDictionary dictionaryWithDictionary:mutableDict];
}

- (NSString *)description 
{
    return [NSString stringWithFormat:@"%@", [self dictionaryRepresentation]];
}

#pragma mark - Helper Method
- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict
{
    id object = [dict objectForKey:aKey];
    return [object isEqual:[NSNull null]] ? nil : object;
}


#pragma mark - NSCoding Methods

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];

    self.status = [aDecoder decodeDoubleForKey:kAccountManagerStatus];
    self.userId = [aDecoder decodeObjectForKey:kAccountManagerUserId];
    self.userName = [aDecoder decodeObjectForKey:kAccountManagerUserName];
    self.internalBaseClassIdentifier = [aDecoder decodeObjectForKey:kAccountManagerId];
    self.regTime = [aDecoder decodeObjectForKey:kAccountManagerRegTime];
    self.userPwd = [aDecoder decodeObjectForKey:kAccountManagerUserPwd];
    self.email = [aDecoder decodeObjectForKey:kAccountManagerEmail];
    self.nickName = [aDecoder decodeObjectForKey:kAccountManagerNickName];
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{

    [aCoder encodeDouble:_status forKey:kAccountManagerStatus];
    [aCoder encodeObject:_userId forKey:kAccountManagerUserId];
    [aCoder encodeObject:_userName forKey:kAccountManagerUserName];
    [aCoder encodeObject:_internalBaseClassIdentifier forKey:kAccountManagerId];
    [aCoder encodeObject:_regTime forKey:kAccountManagerRegTime];
    [aCoder encodeObject:_userPwd forKey:kAccountManagerUserPwd];
    [aCoder encodeObject:_email forKey:kAccountManagerEmail];
    [aCoder encodeObject:_nickName forKey:kAccountManagerNickName];
}

- (id)copyWithZone:(NSZone *)zone
{
    AccountManager *copy = [[AccountManager alloc] init];
    
    if (copy) {

        copy.status = self.status;
        copy.userId = [self.userId copyWithZone:zone];
        copy.userName = [self.userName copyWithZone:zone];
        copy.internalBaseClassIdentifier = [self.internalBaseClassIdentifier copyWithZone:zone];
        copy.regTime = [self.regTime copyWithZone:zone];
        copy.userPwd = [self.userPwd copyWithZone:zone];
        copy.email = [self.email copyWithZone:zone];
        copy.nickName = [self.nickName copyWithZone:zone];
    }
    
    return copy;
}


#pragma mark - 业务逻辑

static AccountManager *userModel = nil;
static dispatch_once_t rootOnceToken;
+ (AccountManager *)shareAccountManager
{
    
    dispatch_once(&rootOnceToken, ^
                  {
                      userModel = [AccountManager readUserInfoModel];
                      if (userModel == nil)
                      {
                          userModel = [[AccountManager alloc]init];
                      }
                  });
    
    return userModel;
}

+ (AccountManager *)readUserInfoModel
{
    NSData *data = [[NSData alloc] initWithContentsOfFile:[AccountManager getFilePath]];
    
    // 2,创建一个反序列化器,把要读的数据 传给它,让它读数据
    NSKeyedUnarchiver *unrachiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    
    // 3,从反序列化器中解码出数组
    AccountManager *account = (AccountManager *) [unrachiver decodeObject];
    // 4 结束解码
    [unrachiver finishDecoding];
    
    return account;
}

+ (NSString *)getFilePath
{
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];//Appending 添加 Component 成分 Directory目录;
}

- (BOOL)logoutAccount
{
    NSFileManager *fmanager=[NSFileManager defaultManager];
    BOOL isSucceed = [fmanager removeItemAtPath:[AccountManager getFilePath] error:nil];
    
    
    if (isSucceed)
    {
        //释放单利
        userModel = nil;
        rootOnceToken = 0l;
    }
    
    [DataLocalManager logoutAccount];
    return isSucceed;
}

- (BOOL)storeAccountInfo
{
    //    把原本不能够直接写入到文件中的对象(_array)--->>编码成NSData--->writeToFile
    // 1,创建一个空的data(类似于一个袋子),用来让序列化器把 编码之后的data存放起来
    NSMutableData *data = [[NSMutableData alloc] init];
    
    // 2,创建一个序列化器,并且给它一个空的data,用来存放编码之后的数据
    NSKeyedArchiver *archive = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    
    // 3,把数组进行编码
    [archive encodeObject:self];//encode 编码
    // 4,结束编码
    [archive finishEncoding];
    
    // 5,把data写入文件
    BOOL isSuccees = [data writeToFile:[AccountManager getFilePath] atomically:YES];
    
    return isSuccees;
}


@end
